package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aerotechnic.dao.interfaces.PhaseDaoIn;
import com.aerotechnic.entities.Jalon;
import com.aerotechnic.entities.Phase;

@Repository("PhaseDao")
public class PhaseDao implements PhaseDaoIn {
	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(Phase phase) {
		// TODO Auto-generated method stub
		getCurrentSession().save(phase);
	}

	@Override
	public void update(Phase phase) {
		// TODO Auto-generated method stub
		getCurrentSession().update(phase);
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub
		getCurrentSession().delete(findByID(id));
	}

	@Override
	public Phase findByID(Long id) {
		// TODO Auto-generated method stub
		List<Phase> tempList=getCurrentSession().createQuery("from Phase where id = "+id).list();
		return  tempList.isEmpty()?null: tempList.get(0);
	}

	@Override
	public List<Phase> findAll() {
		// TODO Auto-generated method stub
		return getCurrentSession().createQuery("from Phase").list();
	}

	@Override
	public List<Phase> find(int jtStartIndex, int jtPageSize) {
		// TODO Auto-generated method stub
		return getCurrentSession().createQuery("from Phase")
				.setFirstResult(jtStartIndex).setMaxResults(jtPageSize).list();
	}

	@Override
	public int countAllPhase() {
				List allPhase = getCurrentSession().createQuery(
						"from Phase ").list();
				return allPhase == null ? 0 : allPhase.size(); 
	}

	@Override
	public Phase getPhaseByCode(int phaseCode) {
		List fetchedPhase = getCurrentSession().createQuery(
				"from Phase  where code = "+phaseCode).list();
		return (Phase) (fetchedPhase.isEmpty() ? null : fetchedPhase.get(0));
	}

}
